package sysUtils

import (
	"errors"
	"github.com/kardianos/service"
	"os"
)

type Run func()
type program struct {
	Run
}

func (p *program) Start(s service.Service) error {
	go p.Run()
	return nil
}

func (p *program) Stop(s service.Service) error {
	return nil
}
func CreateService(run Run, serviceName, DisplayName, Description string) (service.Service, error) {
	svcConfig := &service.Config{
		Name:        serviceName, //服务显示名称
		DisplayName: DisplayName, //服务名称
		Description: Description, //服务描述
	}
	prg := &program{run}
	sys := service.ChosenSystem()
	return sys.New(prg, svcConfig)
}
func GetService(serviceName string) (service.Service, error) {
	svcConfig := &service.Config{
		Name: serviceName, //服务显示名称
	}
	prg := &program{}
	sys := service.ChosenSystem()
	return sys.New(prg, svcConfig)
}
func Install(serviceName, DisplayName, Description string, run Run) error {
	s, err := CreateService(run, serviceName, DisplayName, Description)
	if err != nil {
		return err
	}
	if len(os.Args) > 1 {
		i := os.Args[1]
		switch i {
		case "i": //install
			s.Uninstall()
			err := s.Install()
			if err != nil {
				return err
			}
			return s.Start()
		case "u": //uninstall
			s.Stop()
			return s.Uninstall()
		default:
			return errors.New("命令错误!,参考命令:1安装:install   2.卸载:uninstall")
		}
	}
	s.Run()
	return nil
}
